package com.starblink.home.ui.part

import android.app.Activity
import android.view.LayoutInflater
import androidx.lifecycle.LifecycleOwner
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.guide.SkNoviceManage
import com.starblink.android.basic.guide.bean.SkGuideBusConfig
import com.starblink.android.basic.guide.bean.SkGuideEnum
import com.starblink.android.basic.imgpreload.PreloadResImgUtils
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.urllink.PullUpPageUtils
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.widget.CustomDialog
import com.starblink.basic.ext.load
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.home.R
import com.starblink.home.databinding.FragmentNavHomeBinding
import com.starblink.home.ui.HomeI
import com.starblink.home.ui.NavHomeVM
import com.starblink.library.widget.databinding.AddVHomeAdvertBinding
import com.starblink.library.widget.novice_guide.control.GuidePopStatusControl


/**
 * 首页各组成部分的管家
 * 处理 骨架图 所有接口的同步汇总+骨架显示处理
 */
class HomeApiResultControl(
    var viewBinding: FragmentNavHomeBinding,
    private var vm: NavHomeVM
) {


    fun initAllDataObserve(
        context: Activity,
        owner: LifecycleOwner,
        homeI : HomeI? = null
    ) {
        vm.allApiCompleted.observe(owner) {
            var isCompleted = true
            //这里可以再加各种数据的判断 去切不同的界面
            for ((_, value) in vm.allApiCompleted.value!!) {
                isCompleted = isCompleted && value
            }
            if (isCompleted) {

                //1.5.2新增背景判断
                if (vm.discountMerchantsData.value.isNullOrEmpty() && vm.bannerObserveData.value.isNullOrEmpty()) {
                    viewBinding.fnhContain.setBackgroundResource(R.drawable.ic_home_no_dis_bg)
                } else {
                    viewBinding.fnhContain.setBackgroundResource(com.starblink.basic.style.R.color.gu_text_primary)
                }
                //1.5.2新增banner隐藏
                if (vm.bannerObserveData.value.isNullOrEmpty()) {
                    viewBinding.layHomeBanner.bannerLay.gone()
                } else {
                    viewBinding.layHomeBanner.bannerLay.visible()
                }

                if (viewBinding.page.isRefreshing) {
                    viewBinding.page.finishRefresh()
                }
                //是否开启加载更多
                if (vm.autoLoadMore) {
                    viewBinding.page.setEnableLoadMore(true)
                } else {
                    viewBinding.page.setEnableLoadMore(false)
                }

                if (vm.showSkeleton) {
                    vm.showSkeleton = false
                    viewBinding.page.post {
                        startGuideTask(context, owner)
                        homeI?.initNotification()
                    }
                }
            }
        }
    }

    //显示引导
    private fun startGuideTask(
        context: Activity,
        owner: LifecycleOwner
    ) {

        //任何可能由引导跳转到别的界面，触发或返回时，都尝试判断首页是否有引导没触发，
        //因为数据刷新了，而首页有引导的数据不一定在第一次请求时都拿到了
        FlowBus.with<Boolean>(FlowConst.HOME_GUIDE_NEXT).register(owner) {
            homeGuideJudge()
        }

        //弹出首页广告弹窗 广告优先级在最后
        SkNoviceManage.whetherGuideCanBeDisplayed(
            sceneEnum = SkGuideEnum.HOME_ADVERT_DIALOG,
            //弹出即将状态置为false
            oncePopSetFalse = false,
            canPop = {
                //弹出广告页
                if (UserDataCenter.currentIndex == 0) {
                    showAdvertDialog(context)
                }
            }, hasPop = {
            })
    }

    //开始第一个引导
    private fun homeGuideJudge() {

        if (!vm.discountMerchantsData.value.isNullOrEmpty()
            && SkNoviceManage.canShowGuide(SkGuideEnum.HOME_FRG_DISCOUNT_V2)
        ) {
            GuidePopStatusControl.homeScrollToTopOffset(viewBinding.appBar, 0)
            FlowBus.boolFlowBusNotify(SkGuideBusConfig.HOME_FRG_DISCOUNT_V2_NAME)
        } else if (!vm.brandData.value.isNullOrEmpty()
            && SkNoviceManage.canShowGuide(
                SkGuideEnum.HOME_FRG_BRAND_V2,
                jump = true,
                jumpList = arrayListOf(
                    SkGuideEnum.HOME_FRG_DISCOUNT_V2
                )
            )
        ) {
            FlowBus.boolFlowBusNotify(SkGuideBusConfig.HOME_FRG_BRAND_V2_NAME)
        } else if (!vm.feedsObserveData.value.isNullOrEmpty() && SkNoviceManage.canShowGuide(
                SkGuideEnum.HOME_FRG_1_PRODUCT_COLL_V2,
                jump = true,
                jumpList = arrayListOf(
                    SkGuideEnum.HOME_FRG_DISCOUNT_V2,
                    SkGuideEnum.HOME_FRG_BRAND_V2
                )
            )
        ) {
            FlowBus.boolFlowBusNotify(SkGuideBusConfig.HOME_FRG_1_PRODUCT_V2_NAME)
        }
    }


    /**
     * 广告弹窗
     */
    private fun showAdvertDialog(context: Activity) {
        PreloadResImgUtils.popOneResourceF(PreloadResImgUtils.HOME_ADVERT)?.let { resF ->
            if (resF.mainPic != null && resF.jumpUrl != null) {
                val contentBinding =
                    AddVHomeAdvertBinding.inflate(
                        LayoutInflater.from(context),
                        null,
                        false
                    )
                val advertDialog =
                    CustomDialog.Builder(context)
                        .create(contentBinding.root)
                advertDialog.show()
                contentBinding.adImg.load(resF.mainPic)
                contentBinding.closeImg.click {
                    advertDialog.dismiss()
                }

                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        event = TrackEvent.pageExposure.value,
                        spmCnt = GTrackerAssistUtils.fetchPageValue(SpmPageDef.NavHomeAdvertDialog),
                    )
                )
                contentBinding.adImg.click {
                    resF.jumpUrl?.let {
                        PullUpPageUtils.routePageIntercept4Url(
                            activity = context,
                            url = it
                        )
                    }
                    advertDialog.dismiss()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.NavHomeAdvertDialog,
                                SpmElementDef.HomePageResDialogClose
                            )
                        )
                    )
                }
            } else {
                YYLogUtils.e("数据不符合要求，不弹出")
            }
        }
    }
}